package cn.yeezhao.test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class LoadTester {

	private static final String KEYWORD_FILE = "/var/summba/apache_log/apache_24.log";

	// private static final String KEYWORD_FILE = "d:/keyword2.txt";

	public final static int QUERY_SIZE = 240302; // 总查询数

	private int queryPerThread;

	private BufferedReader br = null;
	
	public LoadTester(int threadCount) {
		queryPerThread = QUERY_SIZE / threadCount;
		try {
			br = new BufferedReader(new FileReader(KEYWORD_FILE));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static final Logger log = LogManager.getLogger(LoadTester.class);

	public static void main(String[] args) {
		int threadCount = Integer.parseInt(args[0]);
		long timeInterval = Long.parseLong(args[1]);
		LoadTester loadTester = new LoadTester(threadCount);
		ExecutorService exec = Executors.newFixedThreadPool(threadCount);

		try {
			for (int i = 0; i < threadCount; i++) {
				List<String> queryList = loadTester.getQueryList();
				exec.execute(new TestThread(queryList, timeInterval));
			}
			exec.shutdown();
			loadTester.br.close();
		} catch (Exception e) {
			log.error(e);
		}
	}

	private List<String> getQueryList() throws IOException {
		String line = null;
		List<String> queryList = new ArrayList<String>(queryPerThread);
		for (int j = 0; j < queryPerThread && (line = br.readLine()) != null; j++) {
			queryList.add(line);
		}
		return queryList;
	}


}
